﻿using Npgsql;
using System.Configuration;
using System.Data;


namespace EMR
{
    public static class pssqlHelper
    {
        //连接字符串
        private static readonly string conStr = ConfigurationManager.ConnectionStrings["pssql"].ConnectionString;


        //执行增删改
        //ExecuteNonQuery();
        public static int ExecuteNonQuery(string sql, params NpgsqlParameter[] sqlparameters)
        {
            using (NpgsqlConnection con = new NpgsqlConnection(conStr))
            {
                using (NpgsqlCommand cmd = new NpgsqlCommand(sql, con))
                {
                    if (sqlparameters != null)
                    {
                        cmd.Parameters.AddRange(sqlparameters);
                    }
                    con.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// 执行查询，返回单行ExecuteScalar();
        /// </summary>
        /// <param name="sql">执行语句</param>
        /// <param name="sqlparameters"></param>
        /// <returns></returns>
        public static object ExecuteScalar(string sql, params NpgsqlParameter[] sqlparameters)
        {
            using (NpgsqlConnection  con = new NpgsqlConnection(conStr))
            {
                using (NpgsqlCommand cmd = new NpgsqlCommand(sql, con))
                {
                    if (sqlparameters != null)
                    {
                        cmd.Parameters.AddRange(sqlparameters);
                    }
                    con.Open();
                    return cmd.ExecuteScalar();
                }
            }
        }

        //执行查询，返回多行
        //ExecuteQuery();
        public static object ExecuteQuery(string sql, params NpgsqlParameter[] sqlParameters)
        {
            NpgsqlConnection con = new NpgsqlConnection(conStr); //不能用using ,当使用Reader时 ，con连接不能关闭。
            using (NpgsqlCommand cmd = new NpgsqlCommand(sql, con))
            {
                if (sqlParameters != null)
                {
                    cmd.Parameters.AddRange(sqlParameters);
                }
                try    //防止执行异常时，con无法关闭。
                {
                    con.Open();
                    return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);//使用重载
                }
                catch
                {
                    con.Close();
                    con.Dispose();
                    throw;  //不抛出 会显示 并非所有的代码路径都返回值
                }
            }
        }
    }
}
